#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <time.h>


void log_message(char *filename, const char* format, pid_t sid,time_t seconds,...) {
	FILE *logfile;
	logfile = fopen(filename, "a");
	if (!logfile) return;
	va_list list;
	va_start( list, format );
	vfprintf(logfile, format, list);
	va_end( list );
	fprintf(logfile, "\n");
    fprintf(logfile, "Daemon # %ld  ,  ", sid);
    fprintf(logfile, "with %ld seconds since started,", seconds);
	fclose(logfile);
}

int main(void) {
        
        /* Our process ID and Session ID */
        pid_t pid, sid;
        char  *fname = {0};
        time_t seconds,ref;
        fname =(char *)malloc((strlen("logtest")+1)*sizeof(char));
        strcpy(fname,"logtest");
        /* Fork off the parent process */
        pid = fork();
        if (pid < 0) {
                exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
                exit(EXIT_SUCCESS);
        }

        /* Change the file mode mask */
        umask(0);
                
        /* Open any logs here */        
                
        /* Create a new SID for the child process */
        sid = setsid();
        if (sid < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }
        

        
        /* Change the current working directory */
        if ((chdir("/")) < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }
        
        /* Close out the standard file descriptors */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        
        /* Daemon-specific initialization goes here */
        ref = time (NULL);
        /* The Big Loop */
        while (1) {
           /* Do some task here ... */
           seconds = time (NULL);
           seconds = seconds - ref ;
           sleep(2); /* wait 30 seconds */

           log_message(fname , NULL , sid, seconds);
        }
   exit(EXIT_SUCCESS);
}
